//
//  TestAddressBook.m
//  PrivateCloud
//
//  Created by mars on 13-10-27.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "TestAddressBook.h"
#import "DDContactInfo.h"
#import "DDAddressBookUtils.h"
#import "NSString+md5.h"
#import "DDCommentDic.h"

@implementation TestAddressBook

//5哥～～ 从这里开始
-(void)testRun {
    //读取本地电话本
    CFArrayRef ref = [self readAddressBook];
    if(ref) {
        //存储vcf文件到本地路径
        NSString* filePath = [self saveVCF:ref];
        if(filePath) {
            //从本地路径读取vcf文件
            [self loadVCF:filePath];
        }
        
        CFRelease(ref);
    }
}




-(CFArrayRef)readAddressBook {
    ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef contacts = ABAddressBookCopyArrayOfAllPeople(addressBook);
    [self paintInfo:contacts];
    CFRelease(addressBook);
    return contacts;
}
//判断通讯录数据是否存在
-(BOOL)isContactInfoExist:(DDContactInfo*) contactInfo{
    ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef contacts = ABAddressBookCopyArrayOfAllPeople(addressBook);
    
    BOOL flag = NO;
    for (CFIndex i = 0; i < CFArrayGetCount(contacts); i++) {
        //判断姓名是否相同
        ABRecordRef person = CFArrayGetValueAtIndex(contacts, i);
        NSString *firstName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
//        firstName = (firstName ? firstName : @"");
        NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
//        lastName = (lastName ? lastName : @"");
        NSLog(@"firstname %@,%@",firstName,[contactInfo firstName]);
        NSLog(@"lastname %@,%@",lastName,[contactInfo lastName]);
        if(firstName == nil && contactInfo.firstName== nil){
            
        }
        else if (![firstName isEqualToString:[contactInfo firstName]]) {
            continue;
        }
        if(lastName == nil && contactInfo.lastName == nil) {
            
        }
        else if(![lastName isEqualToString:[contactInfo lastName]]){
            continue;
        }
        
        //判断邮箱是否相同
        BOOL emailFlag = NO;
        ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
        if(ABMultiValueGetCount(emails) == 0 && contactInfo.email == nil){
            emailFlag = true;
        }else{
            if(emails) {
                for (int k = 0; k < ABMultiValueGetCount(emails); k++) {
                    NSString *email = (NSString *)ABMultiValueCopyValueAtIndex(emails, k);
                    if([email isEqualToString:[contactInfo email]]){
                        emailFlag = YES;
                        break;
                    }
                }
            }
        }
        if (emailFlag == NO) {
            continue;
        }
        
        BOOL phoneFlag = NO;
        //判断手机号码是否相同
        ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
        if(phoneNumbers) {
            for (int k = 0; k < ABMultiValueGetCount(phoneNumbers); k++) {
                NSString *label = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phoneNumbers, k));
                NSString *number = (NSString *)ABMultiValueCopyValueAtIndex(phoneNumbers, k);
                NSString *labelLower = [label lowercaseString];
                
                for (NSString* num in contactInfo.phoneNums) {
                    if([num isEqualToString:number]){
                        phoneFlag = YES;
                        break;
                    }
                }
                for (NSString* num in contactInfo.workNums) {
                    if([num isEqualToString:number]){
                        phoneFlag = YES;
                        break;
                    }
                }
                for (NSString* num in contactInfo.homeNums) {
                    if([num isEqualToString:number]){
                        phoneFlag = YES;
                        break;
                    }
                }
            }
        }
        
        if (phoneFlag == YES) {
            return YES;
        }
        
        
    }
    return NO;
}

-(void)createVcfWithContactInfos:(NSArray*)infos atPath:(NSString*)path{
    NSString *vcard = @"";
    for (int i = 0; i < [infos count]; i++) {
        DDContactInfo* info = [infos objectAtIndex:i];
        NSString* firstName = (info.firstName ? info.firstName : @"");
        NSString* lastName = (info.lastName ? info.lastName : @"'");
        if(i>0){
            vcard = [vcard stringByAppendingString:@"\n"];
        }
        vcard = [vcard stringByAppendingString:@"BEGIN:VCARD\n"];
        vcard = [vcard stringByAppendingString:@"VERSION:2.1\n"];
        //放入名字
        NSString* fAndLName = [NSString stringWithFormat:@"%@ %@",lastName,firstName];
        fAndLName = [fAndLName quotedPrintableString];
        vcard = [vcard stringByAppendingFormat:@"N;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:%@\n",fAndLName];
        vcard = [vcard stringByAppendingFormat:@"FN;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:%@\n",fAndLName];
        for (NSString* mobileNum in info.phoneNums) {
            vcard = [vcard stringByAppendingFormat:@"TEL;CELL;VOICE:%@\n",mobileNum];
        }
        
        for (NSString* homeNum in info.homeNums) {
            vcard = [vcard stringByAppendingFormat:@"TEL;HOME;VOICE:%@\n",homeNum];
        }
        
        for (NSString* workNum in info.workNums) {
            vcard = [vcard stringByAppendingFormat:@"TEL;WORK;VOICE:%@\n",workNum];
        }
        
        for (NSString* iPhoneNum in info.iphoneNums) {
            vcard = [vcard stringByAppendingFormat:@"TEL;IPHONE;VOICE:%@\n",iPhoneNum];
        }
        
        if(info.email != nil){
            vcard = [vcard stringByAppendingFormat:@"EMAIL;PREF;INTERNET:%@\n",info.email];
        }
        vcard = [vcard stringByAppendingString:@"END:VCARD"];
        
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *folderPath = [paths objectAtIndex:0];
    NSString *filePath = [folderPath stringByAppendingPathComponent:path];
    [vcard writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
//5哥，看这里，生成vcf 格式文本
-(NSString*)generateVCardStringWithContacts:(CFArrayRef)contacts {
    NSInteger counter  = 0;
    NSString *vcard = @"";
    
    for(CFIndex i = 0; i < CFArrayGetCount(contacts); i++) {
        
        ABRecordRef person = CFArrayGetValueAtIndex(contacts, i);
        
        NSString *firstName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        firstName = (firstName ? firstName : @"");
        NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
        lastName = (lastName ? lastName : @"");
        NSString *middleName = (NSString *)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
        NSString *prefix = (NSString *)ABRecordCopyValue(person, kABPersonPrefixProperty);
        NSString *suffix = (NSString *)ABRecordCopyValue(person, kABPersonSuffixProperty);
        NSString *nickName = (NSString *)ABRecordCopyValue(person, kABPersonNicknameProperty);
        NSString *firstNamePhonetic = (NSString *)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
        NSString *lastNamePhonetic = (NSString *)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
        
        NSString *organization = (NSString *)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        NSString *jobTitle = (NSString *)ABRecordCopyValue(person, kABPersonJobTitleProperty);
        NSString *department = (NSString *)ABRecordCopyValue(person, kABPersonDepartmentProperty);
        
        NSString *compositeName = [NSString stringWithFormat:@"%@%@",firstName,lastName];
        
        if(i > 0) {
            vcard = [vcard stringByAppendingFormat:@"\n"];
        }
        
        vcard = [vcard stringByAppendingFormat:@"BEGIN:VCARD\nVERSION:3.0\nN:%@;%@;%@;%@;%@\n",
                 (firstName ? firstName : @""),
                 (lastName ? lastName : @""),
                 (middleName ? middleName : @""),
                 (prefix ? prefix : @""),
                 (suffix ? suffix : @"")
                 ];
        
        vcard = [vcard stringByAppendingFormat:@"FN:%@\n",compositeName];
        if(nickName) vcard = [vcard stringByAppendingFormat:@"NICKNAME:%@\n",nickName];
        if(firstNamePhonetic) vcard = [vcard stringByAppendingFormat:@"X-PHONETIC-FIRST-NAME:%@\n",firstNamePhonetic];
        if(lastNamePhonetic) vcard = [vcard stringByAppendingFormat:@"X-PHONETIC-LAST-NAME:%@\n",lastNamePhonetic];
        
        // Work
        if(organization) vcard = [vcard stringByAppendingFormat:@"ORG:%@;%@\n",(organization?organization:@""),(department?department:@"")];
        
        if(jobTitle) vcard = [vcard stringByAppendingFormat:@"TITLE:%@\n",jobTitle];
        
        // Mail
        ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
        if(emails) {
            for (int k = 0; k < ABMultiValueGetCount(emails); k++) {
                NSString *label = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(emails, k));
                NSString *email = (NSString *)ABMultiValueCopyValueAtIndex(emails, k);
                NSString *labelLower = [label lowercaseString];
                
                vcard = [vcard stringByAppendingFormat:@"EMAIL;type=INTERNET;type=WORK:%@\n",email];
                
                if ([labelLower isEqualToString:@"home"]) vcard = [vcard stringByAppendingFormat:@"EMAIL;type=INTERNET;type=HOME:%@\n",email];
                else if ([labelLower isEqualToString:@"work"]) vcard = [vcard stringByAppendingFormat:@"EMAIL;type=INTERNET;type=WORK:%@\n",email];
                else {//类型解析不出来的
                    counter++;
                    vcard = [vcard stringByAppendingFormat:@"item%d.EMAIL;type=INTERNET:%@\nitem%d.X-ABLabel:%@\n",counter,email,counter,label];
                }
            }
        }
        
        // Tel
        ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
        if(phoneNumbers) {
            for (int k = 0; k < ABMultiValueGetCount(phoneNumbers); k++) {
                NSString *label = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phoneNumbers, k));
                NSString *number = (NSString *)ABMultiValueCopyValueAtIndex(phoneNumbers, k);
                NSString *labelLower = [label lowercaseString];
                
                if ([labelLower isEqualToString:@"mobile"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=CELL:%@\n",number];
                else if ([labelLower isEqualToString:@"home"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=HOME:%@\n",number];
                else if ([labelLower isEqualToString:@"work"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=WORK:%@\n",number];
                else if ([labelLower isEqualToString:@"main"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=MAIN:%@\n",number];
                else if ([labelLower isEqualToString:@"homefax"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=HOME;type=FAX:%@\n",number];
                else if ([labelLower isEqualToString:@"workfax"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=WORK;type=FAX:%@\n",number];
                else if ([labelLower isEqualToString:@"pager"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=PAGER:%@\n",number];
                else if([labelLower isEqualToString:@"other"]) vcard = [vcard stringByAppendingFormat:@"TEL;type=OTHER:%@\n",number];
                else { //类型解析不出来的
                    counter++;
                    vcard = [vcard stringByAppendingFormat:@"item%d.TEL:%@\nitem%d.X-ABLabel:%@\n",counter,number,counter,label];
                }
            }
        }
        
        // Address
        ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);
        if(address) {
            for (int k = 0; k < ABMultiValueGetCount(address); k++) {
                NSString *label = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(label, k));
                NSDictionary *dic = (NSDictionary *)ABMultiValueCopyLabelAtIndex(address, k);
                NSString *labelLower = [label lowercaseString];
                NSString* country = [dic valueForKey:(NSString *)kABPersonAddressCountryKey];
                NSString* city = [dic valueForKey:(NSString *)kABPersonAddressCityKey];
                NSString* state = [dic valueForKey:(NSString *)kABPersonAddressStateKey];
                NSString* street = [dic valueForKey:(NSString *)kABPersonAddressStreetKey];
                NSString* zip = [dic valueForKey:(NSString *)kABPersonAddressZIPKey];
                NSString* countryCode = [dic valueForKey:(NSString *)kABPersonAddressCountryCodeKey];
                NSString *type = @"";
                NSString *labelField = @"";
                counter++;
                
                if([labelLower isEqualToString:@"work"]) type = @"WORK";
                else if([labelLower isEqualToString:@"home"]) type = @"HOME";
                else if(label && [label length] > 0)
                {
                    labelField = [NSString stringWithFormat:@"item%d.X-ABLabel:%@\n",counter,label];
                }
                
                vcard = [vcard stringByAppendingFormat:@"item%d.ADR;type=%@:;;%@;%@;%@;%@;%@\n%@item%d.X-ABADR:%@\n",
                         counter,
                         type,
                         (street ? street : @""),
                         (city ? city : @""),
                         (state ? state : @""),
                         (zip ? zip : @""),
                         (country ? country : @""),
                         labelField,
                         counter,
                         (countryCode ? countryCode : @"")
                         ];
            }
        }
        
        vcard = [vcard stringByAppendingString:@"END:VCARD"];
    }
    
    return vcard;
}

//5哥，这个是解析vcf文件
-(void)parseVCardString:(NSString*)vcardString {
    NSArray *lines = [vcardString componentsSeparatedByString:@"\n"];
    
    for(NSString* line in lines) {
        
        if ([line hasPrefix:@"BEGIN"]) {
            NSLog(@"parse start");
        } else if ([line hasPrefix:@"END"]) {
            NSLog(@"parse end");
        } else if ([line hasPrefix:@"N:"]) {
            NSArray *upperComponents = [line componentsSeparatedByString:@":"];
            NSArray *components = [[upperComponents objectAtIndex:1] componentsSeparatedByString:@";"];
            
            NSString * lastName = [components objectAtIndex:0];
            NSString * firstName = [components objectAtIndex:1];
            
            NSLog(@"name %@ %@",lastName,firstName);
            
        } else if ([line hasPrefix:@"EMAIL;"]) {
            NSArray *components = [line componentsSeparatedByString:@":"];
            NSString *emailAddress = [components objectAtIndex:1];
            NSLog(@"emailAddress %@",emailAddress);
            
        } else if ([line hasPrefix:@"TEL;"]) {
            NSArray *components = [line componentsSeparatedByString:@":"];
            NSString *phoneNumber = [components objectAtIndex:1];
            NSLog(@"phoneNumber %@",phoneNumber);
        }
    }
    
}

-(NSString*)saveVCF:(CFArrayRef)contacts {
    
    NSString *str = @"";
    //    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0) { // 5.0版本用系统自带的
    //        CFDataRef vcards = (CFDataRef)ABPersonCreateVCardRepresentationWithPeople(contacts);
    //        str = [[NSString alloc] initWithData:(NSData *)vcards encoding:NSUTF8StringEncoding];
    //        CFRelease(vcards);
    //    }
    //    else { //4.x 代码在这里哦～
    //        str = [self generateVCardStringWithContacts:contacts];
    //    }
    str = [self generateVCardStringWithContacts:contacts];
    NSLog(@"save vcf str %@",str);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *folderPath = [paths objectAtIndex:0];
    NSString *filePath = [folderPath stringByAppendingPathComponent:@"contacts.vcf"];
    NSLog(@"path----------%@",filePath);
    [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"save vcf to path %@",filePath);
    return filePath;
}

-(NSString*)saveVCFWithPath:(NSString*)path {
    
    NSString *str = @"";
    CFArrayRef ref = [self readAddressBook];
    str = [self generateVCardStringWithContacts:ref];
    NSLog(@"save vcf str %@",str);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *folderPath = [paths objectAtIndex:0];
    NSString *filePath = [folderPath stringByAppendingPathComponent:path];
    NSLog(@"path----------%@",filePath);
    [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"save vcf to path %@",filePath);
    CFRelease(ref);
    return filePath;
}

-(NSMutableArray*)loadVCF:(NSString*)filePath {
    
    NSString* str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0) { // 5.0版本用系统自带的
        NSLog(@"load vcf str %@",str);
        
//        CFDataRef vcardData = (CFDataRef)CFBridgingRetain([str dataUsingEncoding:NSUTF8StringEncoding]);
        CFDataRef vcardData = (CFDataRef)CFBridgingRetain([NSData dataWithContentsOfFile:filePath]);
        ABAddressBookRef book = ABAddressBookCreate();
        ABRecordRef ref = ABAddressBookCopyDefaultSource(book);
        CFArrayRef contacts = ABPersonCreatePeopleInSourceWithVCardRepresentation(ref, vcardData);
        NSLog(@"load vcf form path %@",filePath);
        NSMutableArray* arr = [self paintInfo:contacts];
        
        CFRelease(vcardData);
        CFRelease(book);
        CFRelease(ref);
        return  arr;
    }
    else { //4.x 代码在这里哦～
        [self parseVCardString:str];
        return nil;
    }
    
}


-(NSMutableArray*)getAllContactInfo{
    ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef contacts = ABAddressBookCopyArrayOfAllPeople(addressBook);
    NSMutableArray* allContactInfo = [self paintInfo:contacts];
    CFRelease(addressBook);
    return allContactInfo;
}


-(NSMutableArray*)paintInfo:(CFArrayRef)contacts {
    
    NSMutableArray* contactInfos = [[NSMutableArray alloc]init];
    
    if (contacts == nil) {
        return nil;
    }
    
    for(CFIndex i = 0; i < CFArrayGetCount(contacts); i++) {
        DDContactInfo* contactInfo = [[DDContactInfo alloc]init];
        ABRecordRef person = CFArrayGetValueAtIndex(contacts, i);
        
        NSString *firstName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        NSLog(@"first name: %@",firstName);
        
        NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
        NSLog(@"last name: %@",lastName);
        
        NSString *fName = [NSString stringWithFormat:@"%@ %@",lastName,firstName];
        
        [contactInfo setFirstName:firstName];
        [contactInfo setLastName:lastName];
        [contactInfo setName:fName];
        
        if (firstName != NULL) {
            [contactInfo setName:firstName];
        }
        else{
            [contactInfo setName:lastName];
        }
        if (firstName == nil) {
            firstName = @"";
        }
        if (lastName == nil) {
            lastName = @"" ;
        }
        NSString* fullName = [NSString stringWithFormat:@"%@ %@",lastName,firstName];
        [contactInfo setName:fullName];
        
        
        
        ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
        if(phones) {
            for (int k = 0; k < ABMultiValueGetCount(phones); k++) {
                NSString *phoneMobile = (NSString *)ABMultiValueCopyValueAtIndex(phones, k);
                NSLog(@"mobile: %@",phoneMobile);
                
                NSString *label = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phones, k));
                if(label){
                    NSLog(@"label: %@",label);
                    if([label isEqualToString:MOBILE]){
                        [[contactInfo phoneNums]addObject:phoneMobile];
                    }
                    else if([label isEqualToString:HOME]){
                        [[contactInfo homeNums]addObject:phoneMobile];
                    }
                    else if([label isEqualToString:WORK]){
                        [[contactInfo workNums]addObject:phoneMobile];
                    }
                    else if([label isEqualToString:@"iPhone"]){
                        [[contactInfo iphoneNums]addObject:phoneMobile];
                    }
                    
                }
                
            }
        }
        
        ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
        if(emails) {
            for (int i = 0; i < ABMultiValueGetCount(emails); i++) {
                NSString *workEmail = (NSString *)ABMultiValueCopyValueAtIndex(emails, 0);
                NSLog(@"email: %@",workEmail);
                [contactInfo setEmail:workEmail];
            }
        }
        [contactInfos addObject:contactInfo];
    }
    return contactInfos;
}

-(int)getRemoteContactCount{
    int result = 0;
    DDAddressBookUtils* bookUtils = [[DDAddressBookUtils alloc]init];
    NSString* remoteVcfPath = [bookUtils getRemoteVcfPath];
    if (remoteVcfPath == nil) {
        return result;
    }
    [bookUtils release];
    NSMutableArray* arr = [self loadVCF:remoteVcfPath];
    result = [arr count];
    [arr release];
    return result;
}

@end